package com.activiti.service.impl;

import com.activiti.ReturnT;
import com.activiti.convert.ProcessInstanceInfoConverter;
import com.activiti.model.DeploymentInfo;
import com.activiti.model.FlowForm;
import com.activiti.model.ProcessInstanceInfo;
import com.activiti.model.StartProcessInfo;
import com.activiti.service.ActivitiService;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ActivitiServiceImpl implements ActivitiService {

    @Autowired
    RepositoryService repositoryService;
    @Autowired
    RuntimeService runtimeService;

    @Override
    public ReturnT<DeploymentInfo> deploy(DeploymentInfo deploymentInfo){
        Deployment deploy = repositoryService
                .createDeployment()
                .name(deploymentInfo.getName())
                .category(deploymentInfo.getCategory())
                .key(deploymentInfo.getKey())
                .tenantId(deploymentInfo.getTenantId())
                .addClasspathResource(deploymentInfo.getResource()).deploy();
        if(StringUtils.isEmpty(deploy.getId())){
            return ReturnT.returnFail("流程发布不成功");
        }
        deploymentInfo.setId(deploy.getId());
        deploymentInfo.setDeploymentTime(deploy.getDeploymentTime());
        return ReturnT.returnOK(deploymentInfo);
    }

    @Override
    public ReturnT<ProcessInstanceInfo> startProcessInstance(StartProcessInfo startProcessInfo){
        Map<String, Object> variables=BeanUtils.beanToMap(startProcessInfo.getStartForm());
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(startProcessInfo.getProcessDefinitionKey(), startProcessInfo.getBusinessKey(), variables);
        ProcessInstanceInfoConverter processInstanceInfoConverter=new ProcessInstanceInfoConverter();
        ProcessInstanceInfo processInstanceInfo = processInstanceInfoConverter.convert(processInstance);
        return ReturnT.returnOK(processInstanceInfo);
    }

    @Override
    public void startForm(FlowForm flowForm) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(flowForm.getProcessDefinitionKey(), flowForm.getBusinessKey());
    }


}
